#!/usr/bin/env python3
"""
文本计数统计程序
支持统计字符数、单词数、句子数、代码行、空行、注释行等
"""

import re
import sys
import argparse
from pathlib import Path
from typing import Dict, Tuple


class TextCounter:
    """文本计数器类"""
    
    def __init__(self, file_path: str):
        self.file_path = Path(file_path)
        if not self.file_path.exists():
            raise FileNotFoundError(f"文件不存在: {file_path}")
        
        self.content = self.file_path.read_text(encoding='utf-8')
    
    def count_chars(self) -> int:
        """统计字符数（包括空格和换行符）"""
        return len(self.content)
    
    def count_words(self) -> int:
        """统计单词数（基于空格分隔）"""
        words = re.findall(r'\b\w+\b', self.content)
        return len(words)
    
    def count_sentences(self) -> int:
        """统计句子数（基于句号、问号、感叹号分隔）"""
        sentences = re.split(r'[.!?]+', self.content)
        # 过滤空字符串
        sentences = [s.strip() for s in sentences if s.strip()]
        return len(sentences)
    
    def count_code_lines(self) -> Tuple[int, int, int]:
        """
        统计代码行、空行、注释行
        适用于Python文件
        """
        if not self.file_path.suffix == '.py':
            return 0, 0, 0
        
        lines = self.content.split('\n')
        code_lines = 0
        empty_lines = 0
        comment_lines = 0
        
        in_multiline_comment = False
        
        for line in lines:
            stripped_line = line.strip()
            
            # 检查空行
            if not stripped_line:
                empty_lines += 1
                continue
            
            # 检查多行注释
            if in_multiline_comment:
                comment_lines += 1
                if '"""' in stripped_line or "'''" in stripped_line:
                    in_multiline_comment = False
                continue
            
            # 检查多行注释开始
            if stripped_line.startswith('"""') or stripped_line.startswith("'''"):
                comment_lines += 1
                in_multiline_comment = True
                continue
            
            # 检查单行注释
            if stripped_line.startswith('#'):
                comment_lines += 1
            else:
                code_lines += 1
        
        return code_lines, empty_lines, comment_lines
    
    def get_all_stats(self) -> Dict[str, int]:
        """获取所有统计信息"""
        code_lines, empty_lines, comment_lines = self.count_code_lines()
        
        return {
            'chars': self.count_chars(),
            'words': self.count_words(),
            'sentences': self.count_sentences(),
            'code_lines': code_lines,
            'empty_lines': empty_lines,
            'comment_lines': comment_lines,
            'total_lines': len(self.content.split('\n'))
        }


def main():
    """主函数"""
    parser = argparse.ArgumentParser(
        description='文本计数统计程序 - 统计文本文件的字符数、单词数、句子数等',
        prog='wc.py'
    )
    
    parser.add_argument(
        'file',
        help='要统计的文本文件路径'
    )
    
    parser.add_argument(
        '-c', '--chars',
        action='store_true',
        help='统计字符数'
    )
    
    parser.add_argument(
        '-w', '--words',
        action='store_true',
        help='统计单词数'
    )
    
    parser.add_argument(
        '-s', '--sentences',
        action='store_true',
        help='统计句子数'
    )
    
    parser.add_argument(
        '-a', '--all',
        action='store_true',
        help='显示所有统计信息'
    )
    
    parser.add_argument(
        '--code-lines',
        action='store_true',
        help='统计代码行数（仅对Python文件有效）'
    )
    
    parser.add_argument(
        '--empty-lines',
        action='store_true',
        help='统计空行数'
    )
    
    parser.add_argument(
        '--comment-lines',
        action='store_true',
        help='统计注释行数'
    )
    
    args = parser.parse_args()
    
    try:
        counter = TextCounter(args.file)
        
        if args.all:
            stats = counter.get_all_stats()
            print(f"文件: {args.file}")
            print(f"字符数: {stats['chars']}")
            print(f"单词数: {stats['words']}")
            print(f"句子数: {stats['sentences']}")
            print(f"总行数: {stats['total_lines']}")
            if counter.file_path.suffix == '.py':
                print(f"代码行: {stats['code_lines']}")
                print(f"空行数: {stats['empty_lines']}")
                print(f"注释行: {stats['comment_lines']}")
            return
        
        # 单个统计项
        if args.chars:
            print(f"字符数: {counter.count_chars()}")
        
        if args.words:
            print(f"单词数: {counter.count_words()}")
        
        if args.sentences:
            print(f"句子数: {counter.count_sentences()}")
        
        if args.code_lines:
            code_lines, _, _ = counter.count_code_lines()
            print(f"代码行: {code_lines}")
        
        if args.empty_lines:
            _, empty_lines, _ = counter.count_code_lines()
            print(f"空行数: {empty_lines}")
        
        if args.comment_lines:
            _, _, comment_lines = counter.count_code_lines()
            print(f"注释行: {comment_lines}")
        
        # 如果没有指定任何参数，显示所有基础统计
        if not any([args.chars, args.words, args.sentences, args.code_lines, 
                   args.empty_lines, args.comment_lines]):
            stats = counter.get_all_stats()
            print(f"字符数: {stats['chars']}")
            print(f"单词数: {stats['words']}")
            print(f"句子数: {stats['sentences']}")
    
    except FileNotFoundError as e:
        print(f"错误: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"处理文件时发生错误: {e}")
        sys.exit(1)


if __name__ == '__main__':
    main()